﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Text;
using System.IO;

using BusinessManagementStudio.Models.BusinessLogic;
using BusinessManagementStudio.Models.BusinessObject.Entities;
using BusinessManagementStudio.Models.BusinessObject.Services;
using BusinessManagementStudio.ViewModel;
using BusinessManagementStudio.Utilities;
using BusinessManagementStudio.Utilities.PDF_Templates;
using BusinessManagementStudio.Utilities.Excel_Templates;

namespace BusinessManagementStudio.Controllers
{
    public class QuotationAndInvoiceController : Controller
    {
        private CompanyService cs = new CompanyService();
        private CompanyRealOrder cro = new CompanyRealOrder();
        private FMService fms = new FMService();
        private OrderService os = new OrderService();
        private QuotationService qs = new QuotationService();
        private InvoiceService invs = new InvoiceService();
        private InvoiceNoStatusService ins = new InvoiceNoStatusService();
        private OrderQuotationView oq = new OrderQuotationView();
        private QuotationAndInvoiceLogic qil = new QuotationAndInvoiceLogic();
        private ClientService clnts = new ClientService();
        
        //
        // GET: /QuotationInvoice/
        public ActionResult Index()
        {
            Company company = new Company();
            company.CompanyNameList = cs.GetCompanyNameList();

            return View(company);
        }

        //
        // GET: /Controller/MyAction/{id}
        [HttpPost]
        public ActionResult Switch(FormCollection collection)
        {
            String[] AllKeys = collection.AllKeys;
            bool isCompany = qil.HasSpecificName(AllKeys, "Company");
            bool isSearch = qil.HasSpecificName(AllKeys, "Search");

            if (isCompany == true && isSearch == false)
            {
                #region Company Selection Only
                var selectedValue = collection["Company"];

                if (selectedValue == "7")
                {
                    cro.ViewName = "JLLORDERSearch";
                    cro.orderList = os.GetSpecificCompanyOrders("7");
                }
                else if (selectedValue == "3")
                {
                    cro.ViewName = "JLLPOSearch";
                    cro.orderList = os.GetSpecificCompanyOrders("3");
                }
                #endregion
            }
            else if (isCompany == false && isSearch == true)
            {
                String SONum = "", WONum = "", FMCode = "", QuotationNo = "";

                if (TempData["CurrentViewName_Quotation"] != null)
                    cro.ViewName = (String)TempData["CurrentViewName_Quotation"];

                if (cro.ViewName == "JLLORDERSearch")
                {
                    #region Company 7
                    SONum = collection["SONo"];
                    WONum = collection["WONo"];

                    if (SONum != "")
                        cro.orderList = os.GetOrders_ByServiceNO(SONum);
                    
                    if (WONum != "")
                        cro.orderList = os.GetOrders_ByWorkOrderNO(WONum);
                    
                    if (SONum != "" && WONum != "")
                        cro.orderList = os.GetOrders_ByServiceNOAndWorkOrderNO(SONum, WONum);
                    #endregion
                }
                else if (cro.ViewName == "JLLPOSearch")
                {
                    #region Company 3
                    FMCode = collection["FMCode"];
                    QuotationNo = collection["QuotationNo"];

                    if (FMCode != "")
                        cro.orderList = os.GetOrders_ByFMCode(FMCode);

                    if (QuotationNo != "")
                        cro.orderList = os.GetOrders_ByQuotationNo(QuotationNo);

                    if (FMCode != "" && QuotationNo != "")
                        cro.orderList = os.GetOrders_ByFMCodeAndQuotationNo(FMCode, QuotationNo);

                    #endregion
                }
            }

            cro.fm = new FM();
            cro.fm.FMNameList = fms.GetFMNameList();
            cro.company = new Company();
            cro.company.CompanyNameList = cs.GetCompanyNameList();
            if (TempData["UserObj"] != null)
                cro.CurrentUser = (User)TempData["UserObj"];

            TempData["CurrentViewName_Quotation"] = cro.ViewName;
            TempData["Quotation_Invoice_Model"] = cro;

            return View(cro.ViewName, cro);
        }

        [HttpPost]
        public ActionResult Search(String SONo, String WONo)
        {
            String CurrView = "";

            if (TempData["Quotation_Invoice_Model"] != null)
                cro = (CompanyRealOrder)TempData["Quotation_Invoice_Model"];

            if (TempData["CurrentViewName_Quotation"] != null)
                CurrView = (String)TempData["CurrentViewName_Quotation"];

            if (CurrView == "JLLORDERSearch")
            {
                cro.ViewName = "JLLORDERSearch";
                if (SONo != "" || SONo != null)
                    cro.orderList = os.GetOrders_ByServiceNO(SONo);
                else if (WONo != "" || WONo != null)
                    cro.orderList = os.GetOrders_ByWorkOrderNO(WONo);
            }
            else if (CurrView == "JLLPOSearch")
            {
                cro.ViewName = "JLLPOSearch";
                cro.orderList = os.GetSpecificCompanyOrders("3");
            }

            cro.fm = new FM();
            cro.fm.FMNameList = fms.GetFMNameList();
            cro.company = new Company();
            cro.company.CompanyNameList = cs.GetCompanyNameList();
            if (TempData["UserObj"] != null)
                cro.CurrentUser = (User)TempData["UserObj"];

            TempData["CurrentViewName_Quotation"] = cro.ViewName;
            TempData["Quotation_Invoice_Model"] = cro;

            return View(cro.ViewName, cro);
        }

        public ActionResult JLLORDERQuotation(String ServiceOrderNo)
        {
            Order order = os.GetOrder_ByServiceNO(ServiceOrderNo);
            order.QuotationCreationDate = DateTime.Now;
            order.QuotationNo = os.GetNextQuotationNo("7");

            return View(order);
        }

        public ActionResult JLLORDERQuotation_View(String ServiceOrderNo)
        {
            OrderQuotationView JllOrderView = new OrderQuotationView();
            JllOrderView.CompletedOrder = os.GetOrder_ByServiceNO(ServiceOrderNo);
            JllOrderView.QuotationList = qs.GetOrderQuotation_ByServiceNO(ServiceOrderNo);
            JllOrderView.Location = JllOrderView.CompletedOrder.Location;
            JllOrderView.ServiceDetail = JllOrderView.QuotationList[0].ServiceDetail;
            JllOrderView.VendorNo = JllOrderView.QuotationList[0].VendorNo;
            DateTime WrkCompletionDate = TimeZoneInfo.ConvertTimeFromUtc(JllOrderView.QuotationList[0].WorkCompletionDate, TimeZoneInfo.Local);
            JllOrderView.WorkCompletionDate = WrkCompletionDate;
            JllOrderView.TotalAmount = JllOrderView.QuotationList[0].TotalAmount;
            return View(JllOrderView);
        }

        public ActionResult JLLORDERInvoice_View(String ServiceOrderNo)
        {
            OrderInvoiceView JllOrderView = new OrderInvoiceView();
            JllOrderView.CompletedOrder = os.GetOrder_ByServiceNO(ServiceOrderNo);
            JllOrderView.JllQuotation = qs.GetOrderQuotation_ByServiceNO(ServiceOrderNo);
            JllOrderView.Location = JllOrderView.CompletedOrder.Location;
            JllOrderView.ServiceDetail = JllOrderView.JllQuotation[0].ServiceDetail;
            JllOrderView.VendorNo = JllOrderView.JllQuotation[0].VendorNo;
            DateTime WrkCompletionDate = TimeZoneInfo.ConvertTimeFromUtc(JllOrderView.JllQuotation[0].WorkCompletionDate, TimeZoneInfo.Local);
            JllOrderView.WorkCompletionDate = WrkCompletionDate;
            JllOrderView.TotalAmount = JllOrderView.JllQuotation[0].TotalAmount;
            return View(JllOrderView);
        }

        public ActionResult JLLPOQuotation_View(String QuotationNo)
        {
            OrderQuotationView JllPOView = new OrderQuotationView();
            JllPOView.CompletedOrder = os.GetOrder_ByQuotationNo(QuotationNo);
            JllPOView.QuotationList = qs.GetOrderQuotation_ByQuotationNo(QuotationNo);
            JllPOView.Location = JllPOView.CompletedOrder.Location;
            JllPOView.ServiceDetail = JllPOView.QuotationList[0].ServiceDetail;
            JllPOView.VendorNo = JllPOView.QuotationList[0].VendorNo;
            DateTime WrkCompletionDate = TimeZoneInfo.ConvertTimeFromUtc(JllPOView.QuotationList[0].WorkCompletionDate, TimeZoneInfo.Local);
            JllPOView.WorkCompletionDate = WrkCompletionDate;
            JllPOView.TotalAmount = JllPOView.QuotationList[0].TotalAmount;
            JllPOView.PONo = JllPOView.QuotationList[0].PONo;
            return View(JllPOView);
        }

        public ActionResult JLLPOInvoice_View(String QuotationNo)
        {
            OrderInvoiceView JllPOView = new OrderInvoiceView();
            JllPOView.CompletedOrder = os.GetOrder_ByQuotationNo(QuotationNo);
            JllPOView.JllQuotation = qs.GetOrderQuotation_ByQuotationNo(QuotationNo);
            JllPOView.Location = JllPOView.CompletedOrder.Location;
            JllPOView.ServiceDetail = JllPOView.JllQuotation[0].ServiceDetail;
            JllPOView.VendorNo = JllPOView.JllQuotation[0].VendorNo;
            DateTime WrkCompletionDate = TimeZoneInfo.ConvertTimeFromUtc(JllPOView.JllQuotation[0].WorkCompletionDate, TimeZoneInfo.Local);
            JllPOView.WorkCompletionDate = WrkCompletionDate;
            JllPOView.TotalAmount = JllPOView.JllQuotation[0].TotalAmount;
            JllPOView.PONo = JllPOView.JllQuotation[0].PONo;
            return View(JllPOView);
        }

        [HttpPost]
        public ActionResult MultipleCommandForQuotation(String command, Quotation jllOrderQuotation, Quotation jllPOQuotation)
        {
            String currentView = "";
            if (TempData["CurrentViewName_Quotation"] != null)
                currentView = (String)TempData["CurrentViewName_Quotation"];

            if (command == "Save")
            {
                if (currentView == "JLLORDERSearch")
                {
                    SaveJLLOrder(jllOrderQuotation);
                    return RedirectToAction("Index", "QuotationAndInvoice");
                }
                else if (currentView == "JLLPOSearch")
                {
                    SaveJLLPO(jllPOQuotation);
                    return RedirectToAction("Index", "QuotationAndInvoice");
                }
            }
            else if (command == "Cancel")
                return RedirectToAction("Index", "QuotationAndInvoice");

            return View();
        }

        [HttpPost]
        public ActionResult MultipleCommandForInvoice(String command)
        {
            String currentView = "";
            if (TempData["CurrentViewName_Quotation"] != null)
                currentView = (String)TempData["CurrentViewName_Quotation"];

            OrderInvoiceQuotation tempObj = null;
            if (TempData["JLLOrderInvoice"] != null)
                tempObj = (OrderInvoiceQuotation)TempData["JLLOrderInvoice"];

            OrderInvoiceQuotation tempObj2 = null;
            if (TempData["JLLPOInvoice"] != null)
                tempObj2 = (OrderInvoiceQuotation)TempData["JLLPOInvoice"];

            if (command == "Save")
            {
                InvoiceNoStatus invoice = new InvoiceNoStatus();

                if (currentView == "JLLORDERSearch")
                {
                    if (tempObj != null)
                    {
                        #region Save To Database
                        tempObj.invoice.IsReceived = false;
                        tempObj.invoice.ReceivedDate = null;
                        tempObj.invoice.ReceivedRef = "";
                        invs.Create(tempObj.invoice);
                        os.UpdateInvoiceNumber(tempObj.invoice.ServiceOrderNo, tempObj.invoice.InvoiceNo, tempObj.invoice.InvoiceDate);

                        // Create Invoice for reference
                        invoice.InvoiceNo = tempObj.invoice.InvoiceNo;
                        String[] splitInvoice = tempObj.invoice.InvoiceNo.Split('-');
                        invoice.Category = splitInvoice[1];
                        invoice.IsValid = true;
                        ins.Create(invoice);
                        #endregion

                        #region Save To PDF
                        PDF_QuotationInvoice pdfInvoice = new PDF_QuotationInvoice();
                        pdfInvoice.QuotationList = tempObj.QuotationList;
                        pdfInvoice.IsQuotation = false;
                        pdfInvoice.IsInvoice = true;
                        pdfInvoice.QuotationNo = tempObj.invoice.QuotationNo;
                        pdfInvoice.QuotationDate = tempObj.order.QuotationCreationDate;
                        pdfInvoice.WorkOrderNo = tempObj.invoice.WorkOrderNo;
                        pdfInvoice.ReferenceNo = tempObj.invoice.ServiceOrderNo;
                        pdfInvoice.VendorNo = tempObj.invoice.VendorNo;
                        pdfInvoice.WorkCompletionDate = tempObj.invoice.WorkCompletionDate;
                        pdfInvoice.Location = tempObj.order.Location;
                        pdfInvoice.ServiceDetail = tempObj.invoice.ServiceDetail;
                        pdfInvoice.IsJLLOrderQuotation = false;
                        pdfInvoice.IsJLLPOQuotation = false;
                        pdfInvoice.InvoiceNo = tempObj.invoice.InvoiceNo;
                        pdfInvoice.InvoiceDate = tempObj.invoice.InvoiceDate;
                        pdfInvoice.IsJLLOrderInvoice = true;
                        pdfInvoice.IsJLLPOInvoce = false;
                        pdfInvoice.JOInvoice = tempObj.invoice;
                        pdfInvoice.JOOrder = tempObj.order;
                        pdfInvoice.PDFDestPath += @"JLLOrder\" + pdfInvoice.QuotationNo + @"\";
                        pdfInvoice.SetPDfFileName();
                        pdfInvoice.client = clnts.GetClient("7");

                        PDFUtil.PDFCreation(pdfInvoice.PDFDestPath, pdfInvoice.PDFFileName, pdfInvoice);
                        #endregion

                        #region Save To Excel
                        ExcelMain excelInvoice = new ExcelMain();
                        excelInvoice.Data = pdfInvoice;
                        excelInvoice.ExcelDestPath += @"JLLOrder\" + excelInvoice.Data.QuotationNo + @"\";
                        excelInvoice.ExcelFileName = pdfInvoice.QuotationNo + ".xlsx";

                        if (Directory.Exists(excelInvoice.ExcelDestPath) == false)
                            Directory.CreateDirectory(excelInvoice.ExcelDestPath);

                        ExcelOpenXmlUtil.CreateQuotationOrInvoiceInExcelFormat("InvNo", excelInvoice);
                        #endregion
                    }

                    return RedirectToAction("Index", "QuotationAndInvoice");
                }
                else if (currentView == "JLLPOSearch")
                {
                    if (tempObj2 != null)
                    {
                        Order tempRecord = os.GetOrder_ByQuotationNo(tempObj2.invoice.QuotationNo);

                        #region Save To Database
                        tempObj2.invoice.PONo = Request.Form["PONo"];
                        tempObj2.invoice.ReceivedDate = null;
                        tempObj2.invoice.ReceivedRef = "";
                        tempObj2.invoice.IsReceived = false;
                        invs.Create(tempObj2.invoice);
                        os.UpdateInvoiceNumberJLLPO(tempObj2.invoice.QuotationNo, tempObj2.invoice.InvoiceNo, tempObj2.invoice.InvoiceDate);

                        // Create Invoice for reference
                        invoice.InvoiceNo = tempObj2.invoice.InvoiceNo;
                        String[] splitInvoice = tempObj2.invoice.InvoiceNo.Split('-');
                        invoice.Category = splitInvoice[1];
                        invoice.IsValid = true;
                        ins.Create(invoice);

                        // Update PO No in Quotation
                        qs.UpdatePONo(tempObj2.invoice.QuotationNo, tempObj2.invoice.PONo);
                        #endregion

                        #region Save To PDF
                        PDF_QuotationInvoice pdfInvoice = new PDF_QuotationInvoice();
                        pdfInvoice.QuotationList = tempObj2.QuotationList;
                        pdfInvoice.IsQuotation = false;
                        pdfInvoice.IsInvoice = true;
                        pdfInvoice.QuotationNo = "JLL-" + tempRecord.FMCode + "-" + tempObj2.order.QuotationCreationDate.ToString("MMyy") + "-" + tempObj2.order.QuotationNo;
                        pdfInvoice.QuotationDate = tempObj2.order.QuotationCreationDate;
                        pdfInvoice.WorkOrderNo = tempObj2.invoice.WorkOrderNo;
                        pdfInvoice.PONo = tempObj2.invoice.PONo;
                        pdfInvoice.ReferenceNo = "JLL-" + tempRecord.FMCode + "/" + tempObj2.order.QuotationCreationDate.ToString("MMyy") + "/" + tempObj2.order.QuotationNo;
                        pdfInvoice.VendorNo = tempObj2.invoice.VendorNo;
                        pdfInvoice.Location = tempObj2.order.Location;
                        pdfInvoice.ServiceDetail = tempObj2.invoice.ServiceDetail;
                        pdfInvoice.IsJLLOrderQuotation = false;
                        pdfInvoice.IsJLLPOQuotation = false;
                        pdfInvoice.InvoiceNo = tempObj2.invoice.InvoiceNo;
                        pdfInvoice.InvoiceDate = tempObj2.invoice.InvoiceDate;
                        pdfInvoice.WorkCompletionDate = tempObj2.invoice.WorkCompletionDate;
                        pdfInvoice.IsJLLOrderInvoice = false;
                        pdfInvoice.IsJLLPOInvoce = true;
                        pdfInvoice.JPOInvoice = tempObj2.invoice;
                        pdfInvoice.JPO = tempObj2.order;
                        pdfInvoice.PDFDestPath += @"JLLPO\" + pdfInvoice.QuotationNo + @"\";
                        pdfInvoice.SetPDfFileName();
                        pdfInvoice.client = clnts.GetClient("3", tempRecord.FMCode);

                        PDFUtil.PDFCreation(pdfInvoice.PDFDestPath, pdfInvoice.PDFFileName, pdfInvoice);
                        #endregion

                        #region Save To Excel
                        ExcelMain excelInvoice = new ExcelMain();
                        excelInvoice.Data = pdfInvoice;
                        excelInvoice.ExcelDestPath += @"JLLPO\" + excelInvoice.Data.QuotationNo + @"\";
                        excelInvoice.ExcelFileName = pdfInvoice.QuotationNo + ".xlsx";

                        if (Directory.Exists(excelInvoice.ExcelDestPath) == false)
                            Directory.CreateDirectory(excelInvoice.ExcelDestPath);

                        ExcelOpenXmlUtil.CreateQuotationOrInvoiceInExcelFormat("InvNo", excelInvoice);
                        #endregion
                    }

                    return RedirectToAction("Index", "QuotationAndInvoice");
                }
            }
            else if (command == "Cancel")
                return RedirectToAction("Index", "QuotationAndInvoice");

            return View();
        }

        [HttpPost]
        public ActionResult MultipleCommandForExport(String command)
        {
            if (command == "ExportToPDF")
            {
                return RedirectToAction("ExportToPDF");
            }

            return View();
        }

        [HttpPost]
        public ActionResult SaveJLLOrder(Quotation jllOrderQuotation)
        {
            List<Quotation> JLLOrderQuotationList = new List<Quotation>();
            var ServiceNo = Request.Form["ServiceOrderNo"];
            var QuotationNo = Request.Form["QuotationNo"];
            Order ExistingOrder = os.GetOrder_ByServiceNO(ServiceNo);
            var WorkOrderNo = Request.Form["WorkOrderNo"];
            var VendorNo = Request.Form["VendorNo"];
            var ServiceDetail = Request.Form["ServiceDetail"];
            String[] tempDateSplit = Request.Form["QuotationCreationDate"].Split('-');
            DateTime QuotationCreationDate = new DateTime(int.Parse(tempDateSplit[0]), int.Parse(tempDateSplit[1]), int.Parse(tempDateSplit[2]), DateTime.Now.Hour, DateTime.Now.Minute, DateTime.Now.Second);
            
            #region Part I - Data Retrieveal
            for (int i = 0; i <= Request.Form.Count; i++)
            {
                
                if(Request.Form["ItemNo[" + i + "]"] != null)
                {
                    var ItemNo = Request.Form["ItemNo[" + i + "]"];
                    var Description = Request.Form["Description[" + i + "]"];
                    var SORItem = Request.Form["SORItem[" + i + "]"];
                    var Qty = Request.Form["Qty[" + i + "]"];
                    var Unit = Request.Form["Unit[" + i + "]"];
                    var Rate = Request.Form["Rate[" + i + "]"];
                    var Amount = Request.Form["Amount[" + i + "]"];
                    var TotalAmount = Request.Form["TotalAmount"];
                    String[] WrkDateTimeSplit = Request.Form["WrkDate"].Split(' ');
                    //String[] WrkTimeSplit = WrkDateTimeSplit[1].Split(':');
                    tempDateSplit = WrkDateTimeSplit[0].Split('-');
                    String tDate = tempDateSplit[1] + " " + int.Parse(tempDateSplit[0]).ToString("00") + ", " + int.Parse(tempDateSplit[2]).ToString("0000");
                    DateTime WrkCompleteionDate = DateTime.Parse(tDate);

                    Quotation tempQuotation = new Quotation();
                    tempQuotation.SequenceNo = i + 1;
                    tempQuotation.ServiceOrderNo = ServiceNo;
                    tempQuotation.QuotationNo = QuotationNo;
                    tempQuotation.WorkOrderNo = WorkOrderNo;
                    tempQuotation.VendorNo = VendorNo;
                    tempQuotation.ServiceDetail = ServiceDetail;
                    tempQuotation.QuotationCreationDate = QuotationCreationDate;
                    tempQuotation.CompanyType = "7";
                    tempQuotation.CompanyName = "JLL - (ORDER)";

                    if (ExistingOrder != null)
                        tempQuotation.Location = ExistingOrder.Location;

                    if(ItemNo == "")
                        tempQuotation.ItemNo = 0;
                    else
                        tempQuotation.ItemNo = int.Parse(ItemNo);

                    tempQuotation.Description = Description;
                    tempQuotation.SORItem = SORItem;
                    if(Qty == "")
                        tempQuotation.Qty = 0;
                    else
                        tempQuotation.Qty = int.Parse(Qty);
                    
                    tempQuotation.Unit = Unit;
                    if(Rate == "")
                        tempQuotation.Rate = 0;
                    else
                        tempQuotation.Rate = decimal.Parse(Rate);

                    if(Amount == "")
                        tempQuotation.Amount = 0;
                    else
                        tempQuotation.Amount = decimal.Parse(Amount);

                    if(TotalAmount == "")
                        tempQuotation.TotalAmount = 0;
                    else
                        tempQuotation.TotalAmount = decimal.Parse(TotalAmount);

                    tempQuotation.WorkCompletionDate = WrkCompleteionDate;

                    JLLOrderQuotationList.Add(tempQuotation);
                }
                else
                    break;
            }
            #endregion

            #region Part II - Save Data (To Database, To Excel and To PDF)
            if (JLLOrderQuotationList.Count > 0)
            {
                Order tempRecord = os.GetOrder_ByServiceNO(ServiceNo);

                #region Part IIa - To Database
                // (a) Save the quotation records
                qs.CreateQuotations(JLLOrderQuotationList);

                // (b) Update Work Service No in JLL Order
                String dbWrkOrderNo = os.GetCurrentWorkOrderNo(ServiceNo);
                String dbQuotationNo = os.GetCurrentQuotationNo(ServiceNo);

                if (dbWrkOrderNo != WorkOrderNo || dbQuotationNo != QuotationNo)
                {
                    Order tOrder = new Order();
                    tOrder = tempRecord;
                    tOrder.ServiceOrderNo = ServiceNo;
                    tOrder.WorkOrderNo = WorkOrderNo;
                    tOrder.QuotationNo = QuotationNo;
                    tOrder.QuotationCreationDate = QuotationCreationDate;
                    tOrder.HasQuotation = true;
                    os.Update(tOrder);
                }
                #endregion

                #region Part IIb - To PDF
                // (c) Save the quotation records into a PDF File
                PDF_QuotationInvoice pdfQuotation = new PDF_QuotationInvoice();
                pdfQuotation.QuotationList = JLLOrderQuotationList;
                pdfQuotation.IsQuotation = true;
                pdfQuotation.IsInvoice = false;
                pdfQuotation.QuotationNo = JLLOrderQuotationList[0].QuotationNo;
                pdfQuotation.QuotationDate = JLLOrderQuotationList[0].QuotationCreationDate;
                pdfQuotation.WorkOrderNo = JLLOrderQuotationList[0].WorkOrderNo;
                pdfQuotation.ReferenceNo = JLLOrderQuotationList[0].ServiceOrderNo;
                pdfQuotation.VendorNo = JLLOrderQuotationList[0].VendorNo;
                pdfQuotation.WorkCompletionDate = JLLOrderQuotationList[0].WorkCompletionDate;
                pdfQuotation.Location = jllOrderQuotation.Location;
                pdfQuotation.ServiceDetail = JLLOrderQuotationList[0].ServiceDetail;
                pdfQuotation.IsJLLOrderQuotation = true;
                pdfQuotation.IsJLLPOQuotation = false;
                pdfQuotation.PDFDestPath += @"JLLOrder\" + pdfQuotation.QuotationNo + @"\";
                pdfQuotation.SetPDfFileName();
                pdfQuotation.client = clnts.GetClient("7");

                if (Directory.Exists(pdfQuotation.PDFDestPath) == false)
                    Directory.CreateDirectory(pdfQuotation.PDFDestPath);

                PDFUtil.PDFCreation(pdfQuotation.PDFDestPath, pdfQuotation.PDFFileName, pdfQuotation);
                #endregion

                #region Part IIc - To Excel
                ExcelMain excelQuotation = new ExcelMain();
                excelQuotation.Data = pdfQuotation;
                excelQuotation.ExcelDestPath += @"JLLOrder\" + excelQuotation.Data.QuotationNo + @"\";
                excelQuotation.ExcelFileName = pdfQuotation.QuotationNo + ".xlsx";

                if (Directory.Exists(excelQuotation.ExcelDestPath) == false)
                    Directory.CreateDirectory(excelQuotation.ExcelDestPath);

                ExcelOpenXmlUtil.CreateQuotationOrInvoiceInExcelFormat("QuotNo", excelQuotation);
                #endregion
            }
            #endregion

            return RedirectToAction("Index");
        }

        [HttpPost]
        public ActionResult SaveJLLPO(Quotation jllPOQuotation)
        {
            List<Quotation> JLLPOQuotationList = new List<Quotation>();
            //var PONo = Request.Form["PONo"];
            var QuotationNo = Request.Form["CompletedOrder.QuotationNo"];
            Order ExistingOrder = os.GetOrder_ByQuotationNo(QuotationNo);

            var WorkOrderNo = Request.Form["WONo"];
            var VendorNo = Request.Form["VendorNo"];
            var ServiceDetail = Request.Form["ServiceDetail"];
            String[] tempDateSplit = Request.Form["CompletedOrder.QuotationCreationDate"].Split('-');
            DateTime QuotationCreationDate = new DateTime(int.Parse(tempDateSplit[0]), int.Parse(tempDateSplit[1]), int.Parse(tempDateSplit[2]), DateTime.Now.Hour, DateTime.Now.Minute, DateTime.Now.Second);

            #region Part I - Data Retrieveal
            for (int i = 0; i <= Request.Form.Count; i++)
            {

                if (Request.Form["ItemNo[" + i + "]"] != null)
                {
                    var ItemNo = Request.Form["ItemNo[" + i + "]"];
                    var Description = Request.Form["Description[" + i + "]"];
                    var SORItem = Request.Form["SORItem[" + i + "]"];
                    var Qty = Request.Form["Qty[" + i + "]"];
                    var Unit = Request.Form["Unit[" + i + "]"];
                    var Rate = Request.Form["Rate[" + i + "]"];
                    var Amount = Request.Form["Amount[" + i + "]"];
                    var TotalAmount = Request.Form["TotalAmount"];
                    String[] WrkDateTimeSplit = Request.Form["WrkDate"].Split(' ');
                    //String[] WrkTimeSplit = WrkDateTimeSplit[1].Split(':');
                    tempDateSplit = WrkDateTimeSplit[0].Split('-');
                    String tDate = tempDateSplit[1] + " " + int.Parse(tempDateSplit[0]).ToString("00") + ", " + int.Parse(tempDateSplit[2]).ToString("0000");
                    DateTime WrkCompleteionDate = DateTime.Parse(tDate);

                    Quotation tempQuotation = new Quotation();
                    tempQuotation.SequenceNo = i + 1;
                    tempQuotation.QuotationNo = QuotationNo;
                    tempQuotation.WorkOrderNo = WorkOrderNo;
                    tempQuotation.VendorNo = VendorNo;
                    tempQuotation.ServiceDetail = ServiceDetail;
                    tempQuotation.QuotationCreationDate = QuotationCreationDate;
                    tempQuotation.CompanyType = "3";
                    tempQuotation.CompanyName = "JLL - (PO)";

                    if (ExistingOrder != null)
                        tempQuotation.Location = ExistingOrder.Location;

                    if(ItemNo == "")
                        tempQuotation.ItemNo = 0;
                    else
                        tempQuotation.ItemNo = int.Parse(ItemNo);

                    tempQuotation.Description = Description;
                    tempQuotation.SORItem = SORItem;
                    if(Qty == "")
                        tempQuotation.Qty = 0;
                    else
                        tempQuotation.Qty = int.Parse(Qty);

                    tempQuotation.Unit = Unit;
                    if(Rate == "")
                        tempQuotation.Rate = 0;
                    else
                        tempQuotation.Rate = decimal.Parse(Rate);
                    
                    if(Amount == "")
                        tempQuotation.Amount = 0;
                    else
                        tempQuotation.Amount = decimal.Parse(Amount);

                    if(TotalAmount == "")
                        tempQuotation.TotalAmount = 0;
                    else
                        tempQuotation.TotalAmount = decimal.Parse(TotalAmount);

                    tempQuotation.WorkCompletionDate = WrkCompleteionDate;

                    JLLPOQuotationList.Add(tempQuotation);
                }
                else
                    break;
            }
            #endregion

            #region Check whether the quotation no has quotation items or not
            List<Quotation> qItems = qs.GetOrderQuotation_ByQuotationNo(QuotationNo);

            if (qItems.Count > 0)
            {
                qs.DeleteQuotations(QuotationNo);
            }

            #endregion

            #region Part II - Save Data (To Database, To Excel and To PDF)
            if (JLLPOQuotationList.Count > 0)
            {
                Order tempRecord = os.GetOrder_ByQuotationNo(QuotationNo);

                #region Part IIa - To Database
                // (a) Save the quotation records
                qs.CreateQuotations(JLLPOQuotationList);

                // (b) Update Work Service No in JLL Order
                String dbWrkOrderNo = os.GetCurrentWorkOrderNo(QuotationNo);

                if (dbWrkOrderNo != WorkOrderNo)
                {
                    Order tPO = new Order();
                    tPO = tempRecord;
                    tPO.VendorNo = VendorNo;
                    tPO.QuotationNo = QuotationNo;
                    tPO.WorkOrderNo = WorkOrderNo;
                    tPO.QuotationCreationDate = QuotationCreationDate;
                    tPO.HasQuotation = true;
                    os.Update(tPO);
                }
                #endregion
                
                #region Part IIb - To PDF
                // (c) Save the quotation records into a PDF File
                PDF_QuotationInvoice pdfQuotation = new PDF_QuotationInvoice();
                pdfQuotation.QuotationList = JLLPOQuotationList;
                pdfQuotation.IsQuotation = true;
                pdfQuotation.IsInvoice = false;
                pdfQuotation.QuotationNo = "JLL-" + tempRecord.FMCode + "-" + JLLPOQuotationList[0].QuotationCreationDate.ToString("MMyy") + "-" + JLLPOQuotationList[0].QuotationNo;
                pdfQuotation.QuotationDate = JLLPOQuotationList[0].QuotationCreationDate;
                pdfQuotation.WorkOrderNo = JLLPOQuotationList[0].WorkOrderNo;
                pdfQuotation.PONo = JLLPOQuotationList[0].PONo;
                pdfQuotation.ReferenceNo = "";
                pdfQuotation.VendorNo = JLLPOQuotationList[0].VendorNo;
                pdfQuotation.WorkCompletionDate = JLLPOQuotationList[0].WorkCompletionDate;
                pdfQuotation.Location = jllPOQuotation.Location;
                pdfQuotation.ServiceDetail = JLLPOQuotationList[0].ServiceDetail;
                pdfQuotation.IsJLLOrderQuotation = false;
                pdfQuotation.IsJLLPOQuotation = true;
                pdfQuotation.PDFDestPath += @"JLLPO\" + pdfQuotation.QuotationNo + @"\";
                pdfQuotation.SetPDfFileName();
                pdfQuotation.client = clnts.GetClient("3", tempRecord.FMCode);

                if (Directory.Exists(pdfQuotation.PDFDestPath) == false)
                    Directory.CreateDirectory(pdfQuotation.PDFDestPath);

                PDFUtil.PDFCreation(pdfQuotation.PDFDestPath, pdfQuotation.PDFFileName, pdfQuotation);
                #endregion

                #region Part IIc - To Excel
                ExcelMain excelQuotation = new ExcelMain();
                excelQuotation.Data = pdfQuotation;
                excelQuotation.ExcelDestPath += @"JLLPO\" + excelQuotation.Data.QuotationNo + @"\";
                excelQuotation.ExcelFileName = pdfQuotation.QuotationNo + ".xlsx";

                if (Directory.Exists(excelQuotation.ExcelDestPath) == false)
                    Directory.CreateDirectory(excelQuotation.ExcelDestPath);

                ExcelOpenXmlUtil.CreateQuotationOrInvoiceInExcelFormat("QuotNo", excelQuotation);
                #endregion
            }
            #endregion

            return RedirectToAction("Index");
        }

        [HttpPost]
        public ActionResult ExportToPDF()
        {
            return View();
        }

        public ActionResult JLLORDERInvoice(String ServiceOrderNo)
        {
            OrderInvoiceQuotation jllOrderInvoiceQuotation = new OrderInvoiceQuotation();
            jllOrderInvoiceQuotation.order = os.GetOrder_ByServiceNO(ServiceOrderNo);
            jllOrderInvoiceQuotation.QuotationList = qs.GetOrderQuotation_ByServiceNO(ServiceOrderNo);
            Invoice jllOrderInvoice = new Invoice();
            jllOrderInvoice.ServiceOrderNo = ServiceOrderNo;
            jllOrderInvoice.QuotationNo = jllOrderInvoiceQuotation.order.QuotationNo;
            jllOrderInvoice.WorkOrderNo = jllOrderInvoiceQuotation.order.WorkOrderNo;
            jllOrderInvoice.InvoiceNo = ins.GetNextInvoiceNo() + "-7";
            jllOrderInvoice.InvoiceDate = DateTime.Now;
            jllOrderInvoice.Location = jllOrderInvoiceQuotation.order.Location;
            jllOrderInvoice.ServiceDetail = jllOrderInvoiceQuotation.QuotationList[0].ServiceDetail;
            jllOrderInvoice.VendorNo = jllOrderInvoiceQuotation.QuotationList[0].VendorNo;
            jllOrderInvoice.CompanyType = "7";
            jllOrderInvoice.CompanyName = "JLL - (ORDER)";
            DateTime WrkCompletionDate = TimeZoneInfo.ConvertTimeFromUtc(jllOrderInvoiceQuotation.QuotationList[0].WorkCompletionDate, TimeZoneInfo.Local);
            jllOrderInvoice.WorkCompletionDate = WrkCompletionDate;
            jllOrderInvoice.TotalAmount = jllOrderInvoiceQuotation.QuotationList[0].TotalAmount;
            jllOrderInvoiceQuotation.invoice = jllOrderInvoice;

            TempData["JLLOrderInvoice"] = jllOrderInvoiceQuotation;

            return View(jllOrderInvoiceQuotation);
        }

        public ActionResult JLLPOInvoice(String QuotationNo)
        {
            OrderInvoiceQuotation jllPOInvoiceQuotation = new OrderInvoiceQuotation();
            jllPOInvoiceQuotation.order = os.GetOrder_ByQuotationNo(QuotationNo);
            jllPOInvoiceQuotation.QuotationList = qs.GetOrderQuotation_ByQuotationNo(QuotationNo);
            Invoice jllPOInvoice = new Invoice();
            jllPOInvoice.QuotationNo = QuotationNo;
            jllPOInvoice.PONo = jllPOInvoiceQuotation.QuotationList[0].PONo;
            jllPOInvoice.WorkOrderNo = jllPOInvoiceQuotation.QuotationList[0].WorkOrderNo;
            jllPOInvoice.VendorNo = jllPOInvoiceQuotation.QuotationList[0].VendorNo;
            jllPOInvoice.CompanyType = "3";
            jllPOInvoice.CompanyName = "JLL - (PO)";
            DateTime WrkCompletionDate = TimeZoneInfo.ConvertTimeFromUtc(jllPOInvoiceQuotation.QuotationList[0].WorkCompletionDate, TimeZoneInfo.Local);
            jllPOInvoice.WorkCompletionDate = WrkCompletionDate;
            jllPOInvoice.Location = jllPOInvoiceQuotation.order.Location;
            jllPOInvoice.ServiceDetail = jllPOInvoiceQuotation.QuotationList[0].ServiceDetail;
            jllPOInvoice.TotalAmount = jllPOInvoiceQuotation.QuotationList[0].TotalAmount;
            jllPOInvoice.InvoiceNo = ins.GetNextInvoiceNo() + "-3";
            jllPOInvoice.InvoiceDate = DateTime.Now;
            jllPOInvoiceQuotation.invoice = jllPOInvoice;

            TempData["JLLPOInvoice"] = jllPOInvoiceQuotation;

            return View(jllPOInvoiceQuotation);
        }

        public ActionResult JLLPOQuotation(String QuotationNo)
        {
            OrderQuotationView oqView = new OrderQuotationView();

            Order jllPO = os.GetOrder_ByQuotationNo(QuotationNo);
            jllPO.QuotationCreationDate = DateTime.Now;

            List<Quotation> itemsList = qs.GetOrderQuotation_ByQuotationNo(QuotationNo);

            oqView.CompletedOrder = jllPO;
            oqView.Location = jllPO.Location;
            oqView.VendorNo = jllPO.VendorNo;
            oqView.QuotationList = itemsList;
            ViewBag.NoOfQuotationItems = itemsList.Count;

            return View(oqView);
        }

        [HttpPost]
        public ContentResult JLLPOQuotationNoModification(string FMCode, string QuotationNo)
        {
            String[] split = QuotationNo.Split('r');
            int currentRevisedNo = 1;

            if (split.Length > 1)
                currentRevisedNo = int.Parse(split[1]) + 1;

            String newQuotationNo = split[0] + "r" + currentRevisedNo;
            Order oldJLLPO = os.GetOrder_ByQuotationNo(QuotationNo);
            oldJLLPO.IsValid = false;

            Order newJLLPO = new Order();
            newJLLPO.FMCode = oldJLLPO.FMCode;
            newJLLPO.HasInvoice = oldJLLPO.HasInvoice;
            newJLLPO.HasQuotation = false;
            newJLLPO.InvoiceCreationDate = oldJLLPO.InvoiceCreationDate;
            newJLLPO.InvoiceNo = oldJLLPO.InvoiceNo;
            newJLLPO.QuotationNo = newQuotationNo;
            newJLLPO.CreationDate = DateTime.Now;
            newJLLPO.IsValid = true;
            newJLLPO.Location = oldJLLPO.Location;
            newJLLPO.QuotationCreationDate = oldJLLPO.QuotationCreationDate;
            newJLLPO.VendorNo = oldJLLPO.VendorNo;
            newJLLPO.WorkOrderNo = oldJLLPO.WorkOrderNo;
            newJLLPO.CompanyType = "3";
            newJLLPO.CompanyName = "JLL - (PO)";

            os.Create(newJLLPO);
            os.UpdateIsValid(oldJLLPO.QuotationNo, oldJLLPO.IsValid);

            #region Quotation Items Searching
            List<Quotation> quotationItems = qs.GetOrderQuotation_ByQuotationNo(QuotationNo);

            if (quotationItems.Count > 0)
            {
                List<Quotation> tempList = new List<Quotation>();
                foreach(Quotation item in quotationItems)
                {
                    Quotation tempItem = item;
                    tempItem.QuotationNo = newQuotationNo;

                    tempList.Add(tempItem);
                }

                qs.CreateQuotations(tempList);
            }
            #endregion

            String result = oldJLLPO.QuotationNo + " is invalid!\n" + newJLLPO.QuotationNo + " is now created!";
            return Content(result);
        }

        [HttpPost]
        public ActionResult EditPOOrder(String FMCode, String QuotationNo, String Location, bool HasQuotation,
            String WorkOrderNo, DateTime QuotationCreationDate, bool HasInvoice, String InvoiceNo, DateTime InvoiceCreationDate, bool isChecked)
        {
            

            return RedirectToAction("Index");
        }
    }
}
